'''
https://leetcode.cn/problems/binary-tree-upside-down/
'''
from typing import Optional


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def upsideDownBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None or root.left is None:
            return root
        left, right = root.left, root.right
        ret = self.upsideDownBinaryTree(left)
        left.left, left.right = right, root
        root.left, root.right = None, None
        return ret
